package com.cr.crandroid.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.cr.crandroid.R;
import com.cr.crandroid.adapter.HomeAdapter;
import com.cr.crandroid.adapter.ImageAdapter;
import com.cr.crandroid.adapter.ImageTitleNumAdapter;
import com.cr.crandroid.utils.CommonConstant;
import com.cr.crandroid.utils.OkHttpManager;
import com.cr.crandroid.vo.CarVo;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerAdapter;
import com.youth.banner.transformer.ZoomOutPageTransformer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HomeFragment extends Fragment {

    private Banner<?, BannerAdapter<?, ?>> banner;
    private HomeAdapter homeAdapter;
    private List<CarVo> cars = new ArrayList<>();
    private CarVo car;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_home, container, false);
        View headerView = inflater.inflate(R.layout.head_home, container, false);
        RecyclerView recyclerView = root.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        homeAdapter = new HomeAdapter(null);
        recyclerView.setAdapter(homeAdapter);
        homeAdapter.setEmptyView(R.layout.empty_home);
        homeAdapter.setHeaderView(headerView);
        homeAdapter.setHeaderWithEmptyEnable(true);
        banner = headerView.findViewById(R.id.banner);
        banner.addBannerLifecycleObserver(this)
                .setPageTransformer(new ZoomOutPageTransformer())
                .start();
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            list.add(R.drawable.pic_item_list_default);
        }
        banner.setAdapter(new ImageAdapter(list));
        RefreshLayout refreshLayout = root.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(layout -> {
            getCarVosList();
            layout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
        });
        refreshLayout.setOnLoadMoreListener(layout -> {
            getCarVosList();
            layout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            Toast.makeText(getActivity(), "没有更多数据了", Toast.LENGTH_SHORT).show();
        });
        homeAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                car = (CarVo) adapter.getData().get(position);
                Bundle bundle = new Bundle();
                bundle.putString("carVo", new Gson().toJson(car, CarVo.class));
                Navigation.findNavController(view).navigate(R.id.action_navigation_home_to_homeItemDetailFragment, bundle);
            }
        });
        getCarVosList();
        return root;
    }


    private void getCarVosList() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> map = new HashMap<>();
                map.put("status", CommonConstant.APPROVE_STATUS_2);
                OkHttpManager.get(CommonConstant.URL + "/car/queryUnApproveCar", map, new Callback() {
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                        String res = response.body().string();
                        JsonObject result = JsonParser.parseString(res).getAsJsonObject();
                        if (Integer.parseInt(String.valueOf(result.get("code"))) != CommonConstant.ERROR) {
                            if (result.get("result") != null) {
                                cars = new Gson().fromJson(result.get("result"), new TypeToken<List<CarVo>>() {
                                }.getType());
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        homeAdapter.setList(cars);
                                        List<CarVo> bannerCars = new ArrayList<>();
                                        if(cars.size()>=3) {
                                            for (int i = 0; i < 3; i++) {
                                                bannerCars.add(cars.get(i));
                                            }
                                        }else{
                                            bannerCars.addAll(cars);
                                        }
                                        banner.setAdapter(new ImageTitleNumAdapter(bannerCars));
                                        banner.setOnBannerListener((data, position) -> {
                                            Bundle bundle = new Bundle();
                                            bundle.putString("carVo", new Gson().toJson(data, CarVo.class));
                                            Navigation.findNavController(getView()).navigate(R.id.action_navigation_home_to_homeItemDetailFragment, bundle);
                                        });
                                    }
                                });

                            }
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {

                    }
                });
            }
        }).start();

    }

}